package com.googlecode.cswish.struts.conversion;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;

import com.googlecode.cswish.model.PageElement;
import com.googlecode.cswish.model.PageElements;
import com.googlecode.cswish.model.PropertyInfo;
import com.googlecode.cswish.model.TextModel;
import com.googlecode.cswish.struts.Action;
import com.googlecode.cswish.struts.Invoker;
import com.googlecode.cswish.struts.spring.BeanIntrospector;
import com.googlecode.cswish.util.OgnlExUtil;
import com.googlecode.cswish.view.DataGrid;

/**
 * List is a simple container 
 * 	 
 * @author jerry.feng Date: 2009-1-13
 */
public class ListPageConverter implements ElementConverter {
	
	private static final Logger logger = Logger.getLogger(ListPageConverter.class);
	
	@Resource
	protected AutoPageConverterManager pageConverterManager;
	
	@Resource
	protected BeanIntrospector beanIntrospector;
	
	@Resource
	private OgnlExUtil ognlExUtil;
	
	@Override
	public PageElement convert(ConversionContext context) {
		// simplify the auto conversion logic , Only convert the first 3 level model 
		if (context.getLevel() >= 3) {
			return null;
		}
		
		PropertyInfo propertyInfo = context.getPropertyInfo();
		if (propertyInfo.isSimpleObj()) {
			return null;
		}

		Class<?> classType = propertyInfo.getTypeClass();
		boolean isArray = classType != null && Collection.class.isAssignableFrom(classType);
		if (isArray) {
			Invoker invoker = context.getInvoker();
			Map<String, String> extraParams = new HashMap<String, String>(4);
			String type = DataGrid.class.getName();
			
			String modelName = propertyInfo.getGenericType();
			
			extraParams.put("itemType", modelName);
			
			PageElements elements = new PageElements(ognlExUtil);
			elements.setExtraParams(extraParams);
			elements.setShortName(propertyInfo.getName());
			elements.setType(type);
			if (Action.VIEW.equals(invoker.methodName)) {
				elements.setTextModel(TextModel.TRUE_WITH_VALUE);
			}
			elements.setArray(isArray);

			// for the class instance , we only add the first generic type as the child element
			PropertyInfo genericPropertyInfo = new PropertyInfo(modelName, propertyInfo.getName());
			ConversionContext newContext = context.clone();
			newContext.setPropertyInfo(genericPropertyInfo);
			PageElement element = pageConverterManager.convert(newContext);
			if (element != null) {
				element.setShortName("[0]");
				elements.addElement(element);
			}
			return elements;
		}
		return null;
	}
}